import React, { useState, forwardRef, useImperativeHandle, useEffect } from "react";
import { Form } from 'antd';
import NewModal from '@/components/Modal';
import DragTable from '@/components/DragTable';
import { ColumnsType } from '../index';

import "./index.less";

interface Props {
	columns: ColumnsType[];
}

const Comp = forwardRef((props: Props, ref) => {
    const [form] = Form.useForm();
    const [columns] = useState(props.columns || []);
    const [dataSource, setDataSource] = useState([]);
    const [colSettingModalObj, setColSettingModalObj] = useState({ open: false, title: '列表配置！' });
    const handleColSettingCancel = () => {
        setColSettingModalObj((pre) => ({ ...pre, open: false }));
    };
    const handleColSettingOpen = () => {
        setColSettingModalObj((pre) => ({ ...pre, open: true }));
    };

    useEffect(() => {
        setDataSource(columns.reduce((init: any, column) => {
            init.push({
                key: column.key || column.dataIndex || 'cz',
                title: column.title,
            });
            return init;
        }, []));
    }, [columns]);

    useImperativeHandle(ref, () => ({
        ...form,
        handleColSettingOpen,
        show: () => handleColSettingOpen(),
    }));

    return (
        <NewModal {...colSettingModalObj} onCancel={handleColSettingCancel}>
            <DragTable
                rowKey="key"
                columns={[{
                    title: '字段',
                    dataIndex: 'title',
                    width: 100,
                }, {
                    title: '显示',
                    dataIndex: 'is_showis_show',
                    width: 100,
                }]}
                dataSource={dataSource}
                pagination={false}
                bordered
            />
        </NewModal>
    );
});

Comp.displayName = 'SearchComp';

export default Comp;